struct Cache<T, E>
where
    T: Fn(E) -> E,
    E: Copy,
{
    query: T,
    value: Option<E>,
}

impl<T, E> Cache<T, E>
where
    T: Fn(E) -> E,
    E: Copy,
{
    fn new(query: T) -> Cache<T, E> {
        Cache { query, value: None }
    }
    // 先查询缓存值 `self.value`，若不存在，则调用 `query` 加载
    fn value(&mut self, arg: E) -> E {
        match self.value {
            Some(v) => v,
            None => {
                let v = (self.query)(arg);
                self.value = Some(v);
                v
            }
        }
    }
}

fn fn_once<F>(func: F)
where
    F: FnOnce(usize) -> bool,//转义所有权，只能被运行一次
{
    println!("{}", func(3));
    //println!("{}", func(4));
}
#[test]
fn test() {
    let x = vec![1, 2, 3];
    fn_once(|z|{z == x.len()})
}


fn fn_once2<F>(func: F)
where
    F: FnOnce(usize) -> bool + Copy,// 改动在这里,实现了copy,调用时使用的是他的拷贝，没有发生所有权的转移
{
    println!("{}", func(3));
    println!("{}", func(4));
}
#[test]
fn test2() {
    let x = vec![1, 2, 3];
    fn_once2(|z|{z == x.len()})
}

#[test]
fn test3(){
    use std::thread;
    let  v = vec![1, 2, 3];
    let handle = thread::spawn( move || {
        println!("Here's a vector: {:?}", v);
    });
    handle.join().unwrap();
    //println!("{:?}", v)
}
fn factory(x:i32) -> Box<dyn Fn(i32) -> i32> {
    let num = 5;

    if x > 1{
        Box::new(move |x| x + num)
    } else {
        Box::new(move |x| x - num)
    }
}